package org.cary.lucene;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;

import org.cary.lucene.search.LuceneSearchEngine;
import org.cary.utils.TaskEngine;

public class IndexQueueConsumer extends Consumer<StoreQueueBean> {
	
	private long period;// 定时执行时间周期，为毫秒	
	private TimerInsert<StoreQueueBean> timerInsert;
	private TaskEngine engine = TaskEngine.getInstance();	
	//当满足本数量时，自动消费
	private static int lucencConsumerNum = 1;//UserProperties.getLuceneConsumerNum();
	
	public IndexQueueConsumer(BlockingQueue<StoreQueueBean> queue, long period) {
		super(queue, lucencConsumerNum);
		this.period = period;
	}
	
	public void stopTimerTask(){
		engine.cancelScheduledTask(timerInsert);
	}

	public void run() {		
		try {
			// 启动定时器
			timerInsert = new TimerInsert<StoreQueueBean>(this);		
			engine.schedule(timerInsert, 0, period);			
			super.run();
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**
	 * 因为list可能同时被消费者、定时器操作，所以这里使用对list操作同步
	 */
	protected void insert(){
		synchronized(list) {
			if(list.size() < 1)
				return ;			
			try {
				LuceneSearchEngine engine = new LuceneSearchEngine();
				engine.changeIndexs((List<StoreQueueBean>) list, lucencConsumerNum);
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				list.clear();
			}
		}
	}

	/**
	 * 定时把数据写入
	 * @author nortan
	 *
	 */
	class TimerInsert<E> extends TimerTask{
		Consumer<E> consumer;
		TimerInsert(Consumer<E> consumer){
			this.consumer = consumer;
		}
		
		@Override
		public void run() {
			consumer.insert();		
		}		
	}
	
	
}

